<?php
/**
 * Class UserWechat
 * Desc  微信用户Controller
 * Create on 2021/9/22 10:31
 * Create by wangyafang
 */

namespace app\api\controller\xyb;


use app\common\library\Sms;
use app\api\model\xyb\UserPlat;
use app\common\model\xyb\UserBelong;
use think\Db;
use Exception;

class UserWechat extends Base
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\api\model\xyb\UserWechat();
    }

    /*更新微信用户*/
    public function update(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $weixin_info= $_POST['rawData'];
        $weixin_info = json_decode($weixin_info,true);

        $wechat_session_key['openid'] = UserBelong::where('user_id',$this->auth->id)->value('openid');
        $wechat_id = $this->model->where('openid',$wechat_session_key['openid'])->value('id');

        if($wechat_id) {//修改微信信息
            $wechatObj = $this->model->where('openid',$wechat_session_key['openid'])->find();
            if(empty($wechatObj['unionid'])) {
                $unionid = (new UserBelong())->where('user_id',$this->auth->id)->value('unionid');
                if ($unionid) {
                    $wechatObj->unionid = $unionid;
                    $wechatObj->save();
                }
            }
            if(!empty($wechatObj['nickname']) && !empty($wechatObj['avatar'])) {
                $this->success('操作成功',[
                    'user_info'=>array(
                        'nickname'=>$wechatObj['nickname'],
                        'avatar'=>xyb_full_url($wechatObj['avatar']),
                        'user_id'=>$this->auth->id,
                        'edit_status'=>0,
                    ),
                ]);
            } else {
                $this->success('操作成功',[
                    'user_info'=>array(
                        'nickname'=>'',
                        'avatar'=>'',
                        'user_id'=>$this->auth->id,
                        'edit_status'=>0,
                    ),
                ]);
            }

        } else {//添加微信信息
            $userWechatModel = $this->model;
            $result = [
                'nickname'=>'',
                'avatar'=>'',
                'openid'=>$wechat_session_key['openid'],
                'unionid'=>(new UserBelong())->where('user_id',$this->auth->id)->value('unionid'),
                'session_key'=>(new UserBelong())->where('user_id',$this->auth->id)->value('session_key'),
                'country'=>$weixin_info['country'],
                'province'=>$weixin_info['province'],
                'city'=>$weixin_info['city'],
                'gender'=>$weixin_info['gender'],
                'createtime'=>time(),
            ];
            Db::startTrans();
            try {
                $userWechatModel->save($result);
                $userPlatObj = (new UserPlat())->where('user_id',$this->auth->id)->find();
                if($userPlatObj) {
                    (new UserPlat())->where([
                        'user_id'=>$this->auth->id,
                    ])->update([
                        'wechat_id'=>$userWechatModel->id,
                    ]);
                } else {
                    (new UserPlat())->save([
                        'user_id'=>$this->auth->id,
                        'wechat_id'=>$userWechatModel->id,
                    ]);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }


            $this->success('操作成功',[
                'user_info'=>array(
                    'nickname'=>'',
                    'avatar'=>'',
                    'user_id'=>$this->auth->id,
                    'edit_status'=>0,
                ),
            ]);
        }
    }

    public function update_nickname_avatar()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->post();
        $avatar = $param['avatar'];
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if(empty($avatar)) {
            $wechat_session_key['openid'] = UserBelong::where('user_id',$this->auth->id)->value('openid');
            $wechat_id =  $this->model->where('openid',$wechat_session_key['openid'])->value('id');
            $userWechat = new \app\api\model\xyb\UserWechat();
            $userWechat->save([
                'nickname'=>$param['nickname'],
            ],['id'=>$wechat_id]);
            $userModel = new \app\admin\model\User();
            $userModel->save([
                'nickname'=>$param['nickname'],
            ],['id'=>$this->auth->id]);
            $userWechat = new \app\api\model\xyb\UserWechat();
            $userWechat->save([
                'nickname'=>$param['nickname'],
            ],['id'=>$wechat_id]);
            if(isset($mobile) && !empty($captcha)) {
                if (!Sms::check($mobile, $captcha, 'register')) {
                    $this->error(__('验证码不正确'));
                }
                $mobileModel = (new UserPlat())->where('mobile',$mobile)->value('mobile');
                if ($mobileModel){
                    $this->error('新手机号已被注册，请更换其他手机号！');
                }
                $userPlat = new UserPlat();
                $userPlat->save([
                    'mobile'=>$mobile,
                ],['user_id'=>$this->auth->id]);
                $userModel = new \app\admin\model\User();
                $userModel->save([
                    'nickname'=>$param['nickname'],
                ],['id'=>$this->auth->id]);
            }
            $userPlatObj = (new UserPlat())->where('user_id',$this->auth->id)->value('mobile');
            $wechatObj = $this->model->where('openid',$wechat_session_key['openid'])->find();
            $this->success('操作成功',[
                'user_info'=>array(
                    'nickname'=>$wechatObj['nickname'],
                    'avatar'=>xyb_full_url($wechatObj['avatar']),
                    'user_id'=>$this->auth->id,
                    'mobile' => $userPlatObj
                ),
            ]);
        } else {
            if(isset($mobile) && !empty($captcha)) {
                if (!Sms::check($mobile, $captcha, 'register')) {
                    $this->error(__('验证码不正确'));
                }
                $mobileModel = (new UserPlat())->where('mobile',$mobile)->value('mobile');
                if ($mobileModel){
                    $this->error('新手机号已被注册，请更换其他手机号！');
                }
                $userPlat = new UserPlat();
                $userPlat->save([
                    'mobile'=>$mobile,
                ],['user_id'=>$this->auth->id]);
                $userModel = new \app\admin\model\User();
                $userModel->save([
                    'mobile'=>$mobile,
                ],['id'=>$this->auth->id]);
            }
            $avatar = str_replace($this->request->domain(),'',$avatar);
            $wechat_session_key['openid'] = UserBelong::where('user_id',$this->auth->id)->value('openid');
            $wechat_id = $this->model->where('openid',$wechat_session_key['openid'])->value('id');
            $userWechat = $this->model;
            $userWechat_info = $userWechat->where('id',$wechat_id)->find();
            if($userWechat_info){
                $userWechat->save([
                    'nickname'=>$param['nickname'],
                    'avatar'=>$avatar,
                ],['id'=>$wechat_id]);
                $userModel = new \app\admin\model\User();
                $userModel->save([
                    'nickname'=>$param['nickname'],
                    'avatar'=>$avatar,
                ],['id'=>$this->auth->id]);
                $userPlatObj = (new UserPlat())->where('user_id',$this->auth->id)->value('mobile');
                $this->success('操作成功',[
                    'user_info'=>array(
                        'nickname'=>$param['nickname'],
                        'avatar'=>xyb_full_url($avatar),
                        'user_id'=>$this->auth->id,
                        'mobile' => $userPlatObj
                    ),
                ]);
            }else{
                $this->error('token错误','',401);
            }
        }

    }

    public function mobile(){
        $userPlatObj = (new UserPlat())->where('user_id',$this->auth->id)->value('mobile');
        if ($userPlatObj){
            $this->success('操作成功',['mobile'=>$userPlatObj]);
        }else{
            $this->error('用户还没有授权手机号');
        }


    }

}